package pk.nak.client.activity;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import pk.nak.client.R;
import pk.nak.enums.AppVars;
import pk.nak.overlays.EatOutItemizedOverlay;
import pk.nak.overlays.EatOutOverlayItem;
import pk.nak.overlays.MapRouteOverlay;
import pk.nak.requests.GetLocationsRequest;
import pk.nak.responses.GetLocationsResponse;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;

public class EatOutMapActivity  extends MapActivity {

	private MapView mv;
	private GetLocationsResponse response = new GetLocationsResponse(){

		@Override
		public void onSuccess(String response) {
			// TODO Auto-generated method stub
			super.onSuccess(response);
			
			List<Overlay> mapOverlay = mv.getOverlays();
			Drawable marker = getResources().getDrawable(R.drawable.location);
			EatOutItemizedOverlay eoio = new EatOutItemizedOverlay(marker,getApplicationContext());
			
			for ( EatOutOverlayItem eooi: this.Overlays()){
				eoio.addOverlay(eooi);
			}
			
			mapOverlay.add(eoio);
			mv.invalidate();
		}
		
	};
	@Override
	protected void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		this.setContentView(R.layout.main);
		this.mv = (MapView) findViewById(R.id.mapView);
		this.mv.setBuiltInZoomControls(true);
		
		MapController mc = this.mv.getController();
		GeoPoint eatoutPoint = new GeoPoint((int)(AppVars.selectedEatOut.getEatoutLatitude() * 1E6), (int)(AppVars.selectedEatOut.getEatoutLongitude() * 1E6));
		GeoPoint devicePoint = new GeoPoint((int)(AppVars.device_lat * 1E6), (int)(AppVars.device_lng * 1E6));
		mc.setCenter(eatoutPoint);
		
		List<Overlay> mapOverlay = this.mv.getOverlays();
		
		EatOutOverlayItem eooi = new EatOutOverlayItem(
				new GeoPoint(
						(int)(AppVars.selectedEatOut.getEatoutLatitude() * 1E6),
						(int)(AppVars.selectedEatOut.getEatoutLongitude() * 1E6)), 
				"Eatout Resturant", 
				AppVars.selectedEatOut.getEatoutName());
		
		Drawable marker = this.getResources().getDrawable(R.drawable.marker);
		EatOutItemizedOverlay eoio = new EatOutItemizedOverlay(marker, getApplicationContext()){

			@Override
			public boolean onTap(GeoPoint p, MapView mapView) {
				//Toast.makeText(mContext, "Location is : " + p.getLatitudeE6() + "," + p.getLongitudeE6(), Toast.LENGTH_LONG).show();
				boolean istap = super.onTap(p, mapView);
				if ( !istap ){
					AppVars.tap_lat = (double)p.getLatitudeE6() / 1e6;
					AppVars.tap_lng = (double)p.getLongitudeE6() / 1e6;
					
					startActivity(new Intent(getApplicationContext(),AddFavouritesActivity.class));
				}
				return istap;
				// TODO Auto-generated method stub
			}
			
		};
		eoio.addOverlay(eooi);
		mapOverlay.add(eoio);
		
		GetLocationsRequest request = new GetLocationsRequest(AppVars.LogedInUserID);
		request.doRequest(response);
		
		this.callMap(devicePoint, eatoutPoint);
	}
	
	private void callMap(GeoPoint srcpoint, GeoPoint destpoint) {
	    List<Overlay> maplistoverlay= this.mv.getOverlays();
	    
	    Drawable drawable = this.getResources().getDrawable(R.drawable.green_a);
	    EatOutItemizedOverlay mapoverlay2 = new EatOutItemizedOverlay(drawable,this);
	    
	    EatOutOverlayItem overlayitem = new EatOutOverlayItem(srcpoint, "", "");
	    
	    mapoverlay2.addOverlay(overlayitem);
	    maplistoverlay.add(mapoverlay2);

	    Drawable drawable2=this.getResources().getDrawable(R.drawable.green_b);
	    EatOutItemizedOverlay mapoverlay3=new EatOutItemizedOverlay (drawable2,this);
	    
	    EatOutOverlayItem overlayitem3 = new EatOutOverlayItem(destpoint, "", "");
	    mapoverlay3.addOverlay(overlayitem3);
	    maplistoverlay.add(mapoverlay3);


	    DrawPath(srcpoint, destpoint, Color.BLUE, this.mv);

	    this.mv.getController().animateTo(srcpoint);
	    this.mv.getController().setZoom(13);
	    //mapview.setStreetView(true);
	    this.mv.setBuiltInZoomControls(true);
	    this.mv.invalidate();


	  }
	  private void DrawPath(GeoPoint src, GeoPoint dest, int color,
	      MapView mMapView01) {



	    // connect to map web service
	    StringBuilder urlString = new StringBuilder();
	    urlString.append("http://maps.google.com/maps?f=d&hl=en");
	    urlString.append("&saddr=");//from
	    urlString.append( Double.toString((double)src.getLatitudeE6()/1.0E6 ));
	    urlString.append(",");
	    urlString.append( Double.toString((double)src.getLongitudeE6()/1.0E6 ));
	    urlString.append("&daddr=");//to
	    urlString.append( Double.toString((double)dest.getLatitudeE6()/1.0E6 ));
	    urlString.append(",");
	    urlString.append( Double.toString((double)dest.getLongitudeE6()/1.0E6 ));
	    urlString.append("&ie=UTF8&0&om=0&output=kml");

	    //System.out.println(urlString);
	    // get the kml (XML) doc. And parse it to get the coordinates(direction route).
	    Document doc = null;
	    HttpURLConnection urlConnection= null;
	    URL url = null;
	    try
	    {
	      url = new URL(urlString.toString());
	      urlConnection=(HttpURLConnection)url.openConnection();
	      urlConnection.setRequestMethod("GET");
	      urlConnection.setDoOutput(true);
	      urlConnection.setDoInput(true);
	      urlConnection.connect();

	      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	      DocumentBuilder db = dbf.newDocumentBuilder();
	      doc = db.parse(urlConnection.getInputStream());

	      if(doc.getElementsByTagName("GeometryCollection").getLength()>0)
	      {
	        //String path = doc.getElementsByTagName("GeometryCollection").item(0).getFirstChild().getFirstChild().getNodeName();
	        String path = doc.getElementsByTagName("GeometryCollection").item(0).getFirstChild().getFirstChild().getFirstChild().getNodeValue() ;
	        
	        String [] pairs = path.split(" ");
	        String[] lngLat = pairs[0].split(","); // lngLat[0]=longitude lngLat[1]=latitude lngLat[2]=height
	        // src
	        GeoPoint startGP = new GeoPoint((int)(Double.parseDouble(lngLat[1])*1E6),(int)(Double.parseDouble(lngLat[0])*1E6));
	        //mMapView01.getOverlays().add(overlayitem);
	        GeoPoint gp1;
	        GeoPoint gp2 = startGP;
	        for(int i=1;i<pairs.length;i++) // the last one would be crash
	        {
	          lngLat = pairs[i].split(",");
	          gp1 = gp2;
	          // watch out! For GeoPoint, first:latitude, second:longitude
	          gp2 = new GeoPoint((int)(Double.parseDouble(lngLat[1])*1E6),(int)(Double.parseDouble(lngLat[0])*1E6));
	          mMapView01.getOverlays().add(new MapRouteOverlay(gp1,gp2,2,color));
	         
	        }
	        //mMapView01.getOverlays().add(new MapRouteOverlay(dest,dest, 3)); // use the default color
	      }
	    }
	    catch (MalformedURLException e)
	    {
	      e.printStackTrace();
	    }
	    catch (IOException e)
	    {
	      e.printStackTrace();
	    }
	    catch (ParserConfigurationException e)
	    {
	      e.printStackTrace();
	    }
	    catch (SAXException e)
	    {
	      e.printStackTrace();
	    }


	  }
	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

}
